<svelte:options immutable={true} />

<script lang="ts">
  import { request, gql } from "graphql-request";

  import { useQuery } from "@sveltestack/svelte-query";

  import TaskQuizItem from "$lib/tasks/all/TaskQuizItem.svelte";
  import TaskFreeStyle from "$lib/tasks/all/TaskFreeStyle.svelte";
  import TaskQuiz from "$lib/tasks/all/TaskQuiz.svelte";

  import type { TaskType } from "$lib/ebm";

  let endpoint = $actixGraphqlEndpoint;
  const TASKS_QUERY = gql`
    query {
      tasks: listTasks {
        id
        quizItemId
        createdAt
        updatedAt
        status
        from
        content {
          id
          createdAt
          updatedAt
          ... on QuizItem {
            __typename
            title
            opstype
            options {
              k
              v
            }
            description
            m3U8
            isMaster
            masterId
            master {
              id
              title
              description
            }
          }
        }
      }
    }
  `;

  const queryResult = useQuery<TaskType[], { message: string }>(
    "tasks",
    async () => {
      const { tasks } = await request(endpoint, TASKS_QUERY);
      return tasks;
    }
  );

  let filter = "all";
</script>

<svelte:head>
  <title>Ebbinghaus Tasks</title>
</svelte:head>

<div class="w-full items-center">
  <h1 class="text-4xl">All Ebbinghaus Tasks</h1>

  <div class="items-center mx-auto py-2">
    <div class="grid grid-cols-4 sm:grid-cols-8 gap-1">
      {#if $queryResult.isLoading}
        Loading...
      {:else if $queryResult.isError}
        Error {$queryResult.error.message}
      {:else}
        {#each $queryResult.data as task, i (task.id)}
          {#if task.content && task.content.__typename === "QuizItem"}
            <TaskQuizItem {task} index={i} />
          {:else if task.content && task.content.__typename === "Quiz"}
            <TaskQuiz {task} index={i} />
          {:else}
            <TaskFreeStyle {task} index={i} />
          {/if}
        {/each}
      {/if}
    </div>
  </div>
</div>
